<?php

namespace app\controller;

use support\Request;
use support\Response;
use GuzzleHttp\Client;
use Webman\View;

class IndexController
{
    private $feishuConfig;
    private $httpClient;
    
    const FEISHU_AUTH_URL = 'https://open.feishu.cn/open-apis/authen/v1/index';
    const FEISHU_TOKEN_URL = 'https://open.feishu.cn/open-apis/authen/v1/access_token';
    const FEISHU_USER_INFO_URL = 'https://open.feishu.cn/open-apis/authen/v1/user_info';
    const APP_TICKET_URL = 'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal';


    public function __construct()
    {
        $this->feishuConfig = config('feishu');
        $this->httpClient = new Client();
    }

    public function index(Request $request)
    {
        $session = $request->session();

        if (!$session->has('user_info')) {
            $redirectUri = url('/callback');
            $authUrl = self::FEISHU_AUTH_URL . '?app_id=' . $this->feishuConfig['app_id'] . '&redirect_uri=' . urlencode($redirectUri);
            return redirect($authUrl);
        }

        return view('index/index', [
            'userInfo' => $session->get('user_info')
        ]);
    }

    public function callback(Request $request)
    {
        $code = $request->get('code');
        if (empty($code)) {
            return new Response(400, [], 'Authorization code not found.');
        }

        try {
            // 1. 获取 app_access_token
            $appTokenResponse = $this->httpClient->post(self::APP_TICKET_URL, [
                'json' => [
                    'app_id' => $this->feishuConfig['app_id'],
                    'app_secret' => $this->feishuConfig['app_secret'],
                ]
            ]);

            $appTokenData = json_decode($appTokenResponse->getBody()->getContents(), true);
            if ($appTokenData['code'] !== 0) {
                 throw new \Exception('Failed to get app_access_token: ' . $appTokenData['msg']);
            }
            $appAccessToken = $appTokenData['app_access_token'];

            // 2. 获取 user_access_token
            $userTokenResponse = $this->httpClient->post(self::FEISHU_TOKEN_URL, [
                'headers' => [
                    'Authorization' => 'Bearer ' . $appAccessToken,
                    'Content-Type' => 'application/json; charset=utf-8',
                ],
                'json' => [
                    'grant_type' => 'authorization_code',
                    'code' => $code,
                ]
            ]);

            $userTokenData = json_decode($userTokenResponse->getBody()->getContents(), true);
            if ($userTokenData['code'] !== 0) {
                throw new \Exception('Failed to get user access token: ' . $userTokenData['msg']);
            }
            
            $userAccessToken = $userTokenData['data']['access_token'];

            // 3. 获取用户信息
            $userInfoResponse = $this->httpClient->get(self::FEISHU_USER_INFO_URL, [
                'headers' => [
                    'Authorization' => 'Bearer ' . $userAccessToken,
                ]
            ]);

            $userInfoData = json_decode($userInfoResponse->getBody()->getContents(), true);
            if ($userInfoData['code'] !== 0) {
                 throw new \Exception('Failed to get user info: ' . $userInfoData['msg']);
            }
            
            // 4. 存储用户信息到 session
            $request->session()->set('user_info', $userInfoData['data']);

            return redirect('/');

        } catch (\Exception $e) {
            // 在生产环境中应记录日志
            return new Response(500, [], 'An error occurred: ' . $e->getMessage());
        }
    }
} 